package com.mapaower.admin.controller;

import com.mapaower.admin.entity.AdminUser;
import com.mapaower.admin.service.AdminUserService;
import com.mapaower.admin.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/admin/users")
public class AdminUserController {

    @Autowired
    private AdminUserService adminUserService;

    /**
     * 获取当前登录管理员信息
     */
    @GetMapping("/profile")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ResponseResult<?>> getCurrentAdminProfile() {
        // 从Spring Security上下文中获取当前登录用户名
        String username = org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication().getName();
        AdminUser adminUser = adminUserService.getAdminUserByUsername(username);
        return ResponseEntity.ok(ResponseResult.success(adminUser));
    }

    /**
     * 获取所有管理员用户列表
     */
    @GetMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ResponseResult<?>> getAllAdminUsers() {
        List<AdminUser> adminUsers = adminUserService.getAllAdminUsers();
        return ResponseEntity.ok(ResponseResult.success(adminUsers));
    }

    /**
     * 根据ID获取管理员用户信息
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ResponseResult<?>> getAdminUserById(@PathVariable Long id) {
        AdminUser adminUser = adminUserService.getAdminUserById(id);
        if (adminUser != null) {
            return ResponseEntity.ok(ResponseResult.success(adminUser));
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 创建新的管理员用户
     */
    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ResponseResult<?>> createAdminUser(@RequestBody AdminUser adminUser) {
        try {
            AdminUser createdUser = adminUserService.createAdminUser(adminUser);
            return ResponseEntity.ok(ResponseResult.success(createdUser));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(ResponseResult.error(e.getMessage()));
        }
    }

    /**
     * 更新管理员用户信息
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ResponseResult<?>> updateAdminUser(@PathVariable Long id, @RequestBody AdminUser adminUser) {
        try {
            AdminUser updatedUser = adminUserService.updateAdminUser(id, adminUser);
            return ResponseEntity.ok(ResponseResult.success(updatedUser));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(ResponseResult.error(e.getMessage()));
        }
    }

    /**
     * 启用管理员用户
     */
    @PutMapping("/{id}/enable")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ResponseResult<?>> enableAdminUser(@PathVariable Long id) {
        boolean result = adminUserService.enableAdminUser(id);
        if (result) {
            return ResponseEntity.ok(ResponseResult.success("管理员用户已启用"));
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 禁用管理员用户
     */
    @PutMapping("/{id}/disable")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ResponseResult<?>> disableAdminUser(@PathVariable Long id) {
        boolean result = adminUserService.disableAdminUser(id);
        if (result) {
            return ResponseEntity.ok(ResponseResult.success("管理员用户已禁用"));
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 删除管理员用户（逻辑删除）
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ResponseResult<?>> deleteAdminUser(@PathVariable Long id) {
        boolean result = adminUserService.deleteAdminUser(id);
        if (result) {
            return ResponseEntity.ok(ResponseResult.success("管理员用户已删除"));
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 更新管理员用户密码
     */
    @PutMapping("/password")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ResponseResult<?>> updatePassword(
            @RequestParam String oldPassword,
            @RequestParam String newPassword) {
        // 从Spring Security上下文中获取当前登录用户ID
        String username = org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication().getName();
        AdminUser adminUser = adminUserService.getAdminUserByUsername(username);
        
        boolean result = adminUserService.updatePassword(adminUser.getId(), oldPassword, newPassword);
        if (result) {
            return ResponseEntity.ok(ResponseResult.success("密码更新成功"));
        } else {
            return ResponseEntity.badRequest().body(ResponseResult.error("旧密码错误"));
        }
    }
}